package com.thread;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author: may
 * @date: 2021年04月08日 21:35
 */
public class TestSemaphore {
    public static void main(String[] args) {
        //同时只能有一个线程能执行
        //Semaphore semaphore = new Semaphore(1);
        //同时只能有2个线程执行
        Semaphore semaphore = new Semaphore(2);

        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println("t1 running");
                TimeUnit.SECONDS.sleep(1);
                System.out.println("t1 running");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }

        }).start();

        new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println("t2 running");
                TimeUnit.SECONDS.sleep(1);
                System.out.println("t2 running");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        }).start();
    }
}
